#include <iostream>
#include "ProjectUtil.h"

using namespace std;

int main(int argc, char *argv[]) {
    
    SimpleCli cli(argv[0]);

    cli.makeOption("-h").longName("--help")
        .description("Show this usage information.");
    cli.makeOption("-l").longName("--limit").required(true).numArgs(1)
        .description("Set the upper limit for the search space.");

    try { cli.parse(argc, argv); }
    catch (invalid_argument ia) { cout << ia.what() << endl; }

    if (cli.isSet("-h")) {
        cli.printUsage(cout);
        return 0;
    }

    int max = atoi(cli.getValue("-l"));
    max++;

    // build list of primes up to the limit
    int* isPrime = new int[max];
    for (int i = 0; i < max; i++) { isPrime[i] = true; };
    isPrime[0] = isPrime[1] = false;

    for (int i = 2; i < max; i++) {
        if (!isPrime[i]) { continue; }
        for (int j = i*2; j < max; j+=i) { isPrime[j] = false; }
    }

    // print all primes
    cout << "{ ";
    int curPrime = 2, numPrinted = 0;
    while (curPrime < max) {
        cout << curPrime << ", ";
        if (++numPrinted % 10 == 0) { cout << endl; }
        while (!isPrime[++curPrime] && curPrime < max);
    }
    cout << " }";

    delete [] isPrime;

    return 0;
}
